package net.tycmc.cty.ctyms.timejob.iems.service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.tycmc.bulb.common.dao.IBaseDAO;
import net.tycmc.bulb.common.dao.ITransactionDAO;
import net.tycmc.bulb.common.util.MapGetter;
import net.tycmc.bulb.common.util.StringUtil;
import net.tycmc.cty.ctyms.timejob.common.DateRegUtil;
import net.tycmc.cty.ctyms.timejob.common.MyConnectDSDAO;
import net.tycmc.cty.ctyms.timejob.common.MyConnectDSTransDAO;
import net.tycmc.cty.ctyms.timejob.common.SMSContentCfg;
import net.tycmc.cty.ctyms.timejob.common.SMSPromptType;
import net.tycmc.cty.ctyms.timejob.iems.dao.MtnFaultDao;
import net.tycmc.cty.ctyms.timejob.iems.dao.SMSInfoDAO;

import org.logicalcobwebs.proxool.configuration.JAXPConfigurator;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class ServiceDeadlineRemindConn {
	IBaseDAO baseDAO;
	private SMSInfoDAO smsInfoDAO;
	private MtnFaultDao malfunctionDiagnosisDAO;
	
	public MtnFaultDao getMalfunctionDiagnosisDAO() {
		return malfunctionDiagnosisDAO;
	}

	public void setMalfunctionDiagnosisDAO(MtnFaultDao malfunctionDiagnosisDAO) {
		this.malfunctionDiagnosisDAO = malfunctionDiagnosisDAO;
	}

	public SMSInfoDAO getSmsInfoDAO() {
		return smsInfoDAO;
	}

	public void setSmsInfoDAO(SMSInfoDAO smsInfoDAO) {
		this.smsInfoDAO = smsInfoDAO;
	}

	public IBaseDAO getBaseDAO() {
		return baseDAO;
	}

	public void setBaseDAO(IBaseDAO baseDAO) {
		this.baseDAO = baseDAO;
	}

	public ITransactionDAO getTranDAO() {
		return tranDAO;
	}

	public void setTranDAO(ITransactionDAO tranDAO) {
		this.tranDAO = tranDAO;
	}

	private ITransactionDAO tranDAO;

	/**
	 * 服务期限提醒
	 */
	public boolean sdrJob() {

		try {
			//获取已安装终端的有效设备
			List<Map<String,Object>> vclList = this.getVehicleInfoList();
			
			//获取已服务期报警的设备Map<设备ID，服务期报警日期>
			Map<String,Object> servLines = this.getServeLinePromptVclInfo();
			if(null==servLines){
				servLines = new HashMap<String,Object>();
			}
			for(Map<String,Object> vcl:vclList){
				//设备进行过服务期报警
				if(servLines.containsKey(MapGetter.getString(vcl,"VehicleID"))){
					//有效提醒
					if(DateRegUtil.compare(MapGetter.getString(servLines,MapGetter.getString(vcl,"VehicleID")), MapGetter.getString(vcl,"TmnlI_InstallTime"), "yyyy-MM-dd")){
						//不进行提醒
						//不处理
					}else{//无效提醒
						this.vclReleaseRemindOfServerDeadLine(vcl);
						if(this.isNeedRemind(MapGetter.getString(vcl,"TmnlI_InstallTime"),Integer.parseInt(MapGetter.getString(vcl, "ServiceDeadline")))){
							this.vclRemindAndSOULast(vcl,true);
						}
					}
				}else{//设备未进行过服务期报警，
					if(this.isNeedRemind(MapGetter.getString(vcl,"TmnlI_InstallTime"),Integer.parseInt(MapGetter.getString(vcl, "ServiceDeadline")))){
						this.vclRemindAndSOULast(vcl,true);
					}
				}
			}
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}

	}
	
	/**
	 * 获取已安装终端的有效设备
	 * @return
	 */
	public List<Map<String, Object>> getVehicleInfoList() {
		String sql = "select VehicleID,VehicleNumber,ISNULL(ServiceDeadline,12) as ServiceDeadline, "
			+"CONVERT(varchar(10),TmnlI_InstallTime,121) as TmnlI_InstallTime  "
			+"from V_VehicleInfo "
			+"where GETDATE()<UsefulLife and Tmnl_SoftEdition is not null and ltrim(rtrim(Tmnl_SoftEdition))!=''"; 
		return baseDAO.execQuery(sql, new Object[] {});
	}
	
	/**
	 * 判断设备是否已提醒过，且提醒时间大于安装时间
	 * @param VehicleID
	 * @return	0:未提醒过；1：有效提醒；2：无效提醒
	 */
	public int vclIsRemind(String VehicleID){
		String sql ="select VehicleID,MsgP_MsgTime,TmnlI_InstallTime,case when MsgP_MsgTime>TmnlI_InstallTime then 1 else 2 end as isValid "
			+"from Msg_Prompt "
			+"inner join V_VehicleInfo on MsgP_VclID=VehicleID "
			+"where MsgP_VclID=? and MsgP_Type=6 ";
		List<Map<String,Object>> vclList = baseDAO.execQuery(sql, new Object[]{VehicleID});
		if(vclList!=null && vclList.size()>0){	//提醒过
			int flag=1;
			for (int i = 0; i < vclList.size();) {
				Map<String,Object> vcl = vclList.get(i);
				String isValid = MapGetter.getString(vcl, "isValid");
				if(isValid.equals("1")){	//有效
					flag=1;
					break;
				}else{	//无效
					flag=2;
					break;
				}
			}
			return flag;
		}else{	//未提醒过
			return 0;
		}
	}
	
	/**
	 * 进行服务期限提醒
	 * @param map
	 * @return
	 */
	public boolean vclRemind(Map<String,Object> map)throws Exception{
		List<String> sqlList = new ArrayList<String>();
		List<Object[]> paramList = new ArrayList<Object[]>();
		
		String VehicleID = MapGetter.getString(map, "VehicleID");
		String VehicleNumber = MapGetter.getString(map, "VehicleNumber");
		String ServiceDeadline = MapGetter.getString(map, "ServiceDeadline");
		String TmnlI_InstallTime = MapGetter.getString(map, "TmnlI_InstallTime");
		//获取设备所属组织机构
		Map<String, Object> codeMap = malfunctionDiagnosisDAO.getDBCode(VehicleID);
		// 获取设备组织机构
		String DBCode = MapGetter.getString(codeMap, "DBCode");
		//服务期限提醒日期
		String remindDate_SMS = this.remindDate(TmnlI_InstallTime, ServiceDeadline,"MM月dd号");
		String remindDate_Web = this.remindDate(TmnlI_InstallTime, ServiceDeadline,"yyyy-MM-dd");
		//向短信记录表和短信发送表插入数据
		String MsgP_DetailMsg_SMS = SMSContentCfg.SMSCCfgServiceDeadline.replace("X_VclNum", VehicleNumber).replace("X_Date", remindDate_SMS);
		
		//发送短信
		List<Map<String,Object>> userList = smsInfoDAO.getSMSUsers("SMSAS_SMSService", DBCode, VehicleID);//获取短信发送人
		String MsgP_SMSRecUser=",";
		for (Map<String, Object> user : userList) {
			String userName = MapGetter.getString(user, "UserName");
			if(StringUtil.isValid(userName)){
				MsgP_SMSRecUser+=userName+",";
			}
		}
		MsgP_SMSRecUser = MsgP_SMSRecUser.equals(",")?"":MsgP_SMSRecUser;
		
		//向提示信息表插入数据
		String MsgP_DetailMsg_Web = SMSContentCfg.SMSCCfgServiceDeadline.replace("X_VclNum", VehicleNumber).replace("X_Date", remindDate_Web);
		String sql_Prompt = "insert into Msg_Prompt(MsgP_VclID,MsgP_MsgTime,MsgP_Type,MsgP_CreateTime,MsgP_DetailMsg,MsgP_SMSRecUser) "
			+"values (?,GETDATE(),?,GETDATE(),?,?)";
		sqlList.add(sql_Prompt);
		paramList.add(new Object[]{VehicleID,SMSPromptType.SMSServiceDeadline,MsgP_DetailMsg_Web,MsgP_SMSRecUser});
		
		map.put("SMSCfgType", 8);	//服务期
		map.put("SMSContent", MsgP_DetailMsg_SMS);	//发送内容
		map.put("PromptType", 8);	//提醒类型：服务期
		map.put("CreateType", 1);	//短信生成方式
		map.put("TabNameShort", "Msg_Prompt");
		map.put("TabName", "Msg_Prompt");
		smsInfoDAO.loadSMSInfo(sqlList, paramList, map,userList);
		return tranDAO.batch(sqlList, paramList);
	}
	
	/**
	 * 解除历史提醒
	 * @param map
	 * @return
	 */
	public int vclReleaseRemind(Map<String,Object> map){
		String VehicleID = MapGetter.getString(map, "VehicleID");
		
		String sql = "update Msg_Prompt set MsgP_ReleaseTime=GETDATE(),MsgP_ReleaseType=1,MsgP_UpdateTime=GETDATE() " +
				"where MsgP_VclID=? and MsgP_Type=6";
		return baseDAO.execUpdate(sql, new Object[]{VehicleID});
	}
	
	/**
	 * 服务期限提醒日期
	 * @param TmnlI_InstallTime	安装日期
	 * @param ServiceDeadline	服务期限
	 * @return
	 */
	public String remindDate(String TmnlI_InstallTime,String ServiceDeadline,String Type) throws Exception{
		int SD = Integer.parseInt(ServiceDeadline);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Calendar maxDate = Calendar.getInstance();
		maxDate.setTime(sdf.parse(TmnlI_InstallTime));
		maxDate.add(Calendar.MONTH, SD);
		
		SimpleDateFormat formatter = new SimpleDateFormat(Type); 
		return formatter.format(maxDate.getTime());	
	}
	
	/**
	 * 根据安装日期和服务期限判断是否需要提醒
	 * 安装日期+（服务期限“减”一个月）<=当前日期<=安装日期+（服务期限）
	 * @param TmnlI_InstallTime	安装日期，格式yyyy-MM-dd
	 * @param ServiceDeadline	服务期限，月数
	 * @return	true:符合条件，需要提醒；false:不符合条件，不需要提醒。
	 */
	public boolean isNeedRemind(String TmnlI_InstallTime,int ServiceDeadline) throws Exception{
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		
		//当前日期
		long currentTime = sdf.parse(sdf.format(new Date())).getTime();
		
		//安装日期+（服务期限“减”一个月）
		Calendar leastDate = Calendar.getInstance();
		leastDate.setTime(sdf.parse(TmnlI_InstallTime));
		leastDate.add(Calendar.MONTH, ServiceDeadline-1);
		long leastTime = sdf.parse(sdf.format(leastDate.getTime())).getTime();
		
		//安装日期+（服务期限）
		Calendar maxDate = Calendar.getInstance();
		maxDate.setTime(sdf.parse(TmnlI_InstallTime));
		maxDate.add(Calendar.MONTH, ServiceDeadline);
		long maxTime = sdf.parse(sdf.format(maxDate.getTime())).getTime();
		
		if(leastTime<=currentTime && currentTime<=maxTime){
			return true;
		}else{
			return false;
		}
	}

	public static void main(String[] args) throws Exception {
		ApplicationContext ctx = null;
		ctx = new ClassPathXmlApplicationContext(new String[] {
				"applicationContext-basedao.xml",
				"applicationContext-generall.xml" });
		JAXPConfigurator.configure("src/proxool.xml", false);
		ServiceDeadlineRemindConn mtnForstConn = (ServiceDeadlineRemindConn) ctx
				.getBean("serviceDeadlineRemindConn");
		if (mtnForstConn == null) {
			System.out.println("null");
		} else {
			mtnForstConn.sdrJob();
		}
	}
	/**
	 * 服务期报警信息入库消息中心系列表中，并更新最新表
	 * 
	 * 20150225 保留提醒历史
	 **/
	private boolean vclRemindAndSOULast(Map<String, Object> map, boolean saveFlag) throws Exception {
		MyConnectDSTransDAO myConnectDSTransDAO=new MyConnectDSTransDAO();
		List<String> sqlList = new ArrayList<String>();
		List<Object[]> paramList = new ArrayList<Object[]>();
		
		String VehicleID = MapGetter.getString(map, "VehicleID");
		String VehicleNumber = MapGetter.getString(map, "VehicleNumber");
		String ServiceDeadline = MapGetter.getString(map, "ServiceDeadline");
		String TmnlI_InstallTime = MapGetter.getString(map, "TmnlI_InstallTime");
		//获取设备所属组织机构
		Map<String, Object> codeMap = malfunctionDiagnosisDAO.getDBCode(VehicleID);
		// 获取设备组织机构
		String DBCode = MapGetter.getString(codeMap, "DBCode");
		//服务期限提醒日期
		String remindDate_SMS = this.remindDate(TmnlI_InstallTime, ServiceDeadline,"MM月dd号");
		
		String MsgP_DetailMsg_SMS = SMSContentCfg.SMSCCfgServiceDeadline.replace("X_VclNum", VehicleNumber).replace("X_Date", remindDate_SMS);		
		//发送短信
		List<Map<String,Object>> userList = smsInfoDAO.getSMSUsers("SMSAS_SMSService", DBCode, VehicleID);//获取短信发送人
		map.put("SMSContent", MsgP_DetailMsg_SMS);	//发送内容、
		map.put("noteState", "1");
		map.put("Position", "null");
		map.put("SMSContentPrompt", SMSContentCfg.SMSCCfgServiceDeadline.replace("X_VclNum", VehicleNumber).replace("X_Date", this.remindDate(TmnlI_InstallTime, ServiceDeadline,"yyyy-MM-dd")));	//提示信息发送内容、
		map.put("SendTime", smsInfoDAO.getTimingSendTime(MapGetter.getString(map, "SMSCfgType")));
		smsInfoDAO.sendNoteInfo(sqlList, paramList, map,userList,"SMSAS_SMSService");
		this.saveOrUpdateServiceLast(sqlList, paramList, map,saveFlag);
		return myConnectDSTransDAO.batch(sqlList, paramList);
	}

	private void saveOrUpdateServiceLast(List<String> sqlList,
			List<Object[]> paramList, Map<String, Object> map, boolean saveFlag) {
		String sql = "";
		if(saveFlag){
			sql = "insert into ServerLine_Prompt(SLP_VclID,SLP_AlarmContent,SLP_AlarmTime)values(?,?,GETDATE());";
		}else{
			
		}
		sqlList.add(sql);
		paramList.add(new Object[]{MapGetter.getString(map, "VehicleID"),MapGetter.getString(map, "SMSContentPrompt")});
	}

	/**
	 * 查询获取进行过服务期报警的设备及其最新的报警事件
	 * @author jiyongtian 20150215新增IEMS3.7优化
	 **/
	private Map<String, Object> getServeLinePromptVclInfo() {
		String sql = "select SLP_VclID,CONVERT(varchar(10),SLP_AlarmTime,121) as PromptTime from ServerLine_Prompt inner join (select MAX(SLP_ID) as keyid from ServerLine_Prompt group by SLP_VclID) as temp on temp.keyid = SLP_ID";
		List<Map<String,Object>> promptVcls = this.baseDAO.execQuery(sql, new Object[]{});
		Map<String,Object> reMap = null;
		if(null!= promptVcls && !promptVcls.isEmpty()){
			reMap = new HashMap<String,Object>();
			for(Map<String,Object> vcl:promptVcls){
				reMap.put(MapGetter.getString(vcl,"SLP_VclID"), MapGetter.getString(vcl,"PromptTime"));
			}
			
		}
		return reMap;
	}
	/**
	 * 解除服务期报警提示信息
	 **/
	private int vclReleaseRemindOfServerDeadLine(Map<String, Object> vcl) {
		MyConnectDSDAO myConnectDSDAO=new MyConnectDSDAO();
		String sql = "update ServerLine_Prompt set SLP_ReleaseTime = GETDATE() where SLP_ID = (select MAX(SLP_ID) from ServerLine_Prompt where SLP_VclID = ?)";
		return myConnectDSDAO.execUpdate(sql, new Object[]{MapGetter.getString(vcl, "VehicleID")});
	}


}